package com.heima.comment.service.impl;


import com.heima.apis.user.UserFeign;
import com.heima.apis.wemedia.WemediaFeign;
import com.heima.comment.service.CommentService;
import com.heima.model.comment.dtos.CommentDto;
import com.heima.model.comment.dtos.CommentLikeDto;
import com.heima.model.comment.dtos.CommentSaveDto;
import com.heima.model.comment.pojos.ApComment;
import com.heima.model.comment.pojos.ApCommentLike;
import com.heima.model.comment.vos.CommentVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.utils.thread.AppThreadLocalUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class CommentServiceImpl implements CommentService {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private UserFeign userFeign;

    @Autowired
    private WemediaFeign wemediaFeign;

    /**
     * 点赞评论
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult likeComment(CommentLikeDto dto) {
        if (dto.getCommentId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        ApComment apComment = mongoTemplate.findById(dto.getCommentId(), ApComment.class);
        if (dto.getOperation() == 0) {
            //点赞 更新点赞数
            apComment.setLikes(apComment.getLikes() + 1);
            mongoTemplate.save(apComment);
            //保存点赞表
            ApCommentLike apCommentLike = new ApCommentLike();
            apCommentLike.setCommentId(dto.getCommentId());
            apCommentLike.setAuthorId(user.getId());
            mongoTemplate.save(apCommentLike);
        } else {
            //取消点赞 更新点赞数
            apComment.setLikes(apComment.getLikes() == 0 ? 0 : apComment.getLikes() - 1);
            mongoTemplate.save(apComment);
            //删除点赞表内容
            Query query = Query.query(Criteria.where("authorId").is(user.getId()).and("commentId").is(dto.getCommentId()));
            mongoTemplate.remove(query, ApCommentLike.class);
        }

        Map<String, Object> map = new HashMap<>();
        map.put("likes", apComment.getLikes());
        return ResponseResult.okResult(map);
    }

    /**
     * app端查询评论列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findAllComment(CommentDto dto) {
        //检查参数
        if (dto.getArticleId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        Query query = Query.query(Criteria.where("entryId").is(dto.getArticleId()).and("createdTime").lt(dto.getMinDate()));
        query.limit(10).with(Sort.by(Sort.Direction.DESC, "createdTime"));
        List<ApComment> apComments = mongoTemplate.find(query, ApComment.class);
        //判断是否登录
        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.okResult(apComments);
        }
        //获取所有评论id
        List<String> idList = apComments.stream().map(comment -> comment.getId()).collect(Collectors.toList());
        //获取评论点赞所有的id
        List<ApCommentLike> apCommentLikes = mongoTemplate.find(Query.query(Criteria.where("authorId").is(user.getId()).and("commentId").in(idList)), ApCommentLike.class);

        List<CommentVo> commentVoList = new ArrayList<>();
        if (apCommentLikes != null) {
            apComments.stream().forEach(comment -> {
                CommentVo vo = new CommentVo();
                BeanUtils.copyProperties(comment, vo);
                for (ApCommentLike apCommentLike : apCommentLikes) {
                    if (comment.getId().equals(apCommentLike.getCommentId())) {
                        vo.setOperation(0);
                        break;
                    }
                }
                commentVoList.add(vo);
            });
        } else {
            return ResponseResult.okResult(apComments);
        }
        return ResponseResult.okResult(commentVoList);
    }

    /**
     * app端保存评论
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveComment(CommentSaveDto dto) {
        //检查参数
        if (dto.getArticleId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //字数要求
        if (dto.getContent() != null && dto.getContent().length() > 140) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE, "评论内容不能超过140个字");
        }
        //判断是否登录
        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //文本垃圾检测
        List<WmSensitive> wmSensitiveList = wemediaFeign.getAll();
        List<String> sensitiveList = wmSensitiveList.stream().map(WmSensitive::getSensitives).collect(Collectors.toList());
        SensitiveWordUtil.initMap(sensitiveList);
        Map<String, Integer> map = SensitiveWordUtil.matchWords(dto.getContent());
        if (map.size() > 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "当前评论中存在违规内容" + map);
        }

        //保存评论
        ApUser apUser = userFeign.findById(user.getId());
        if (apUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE, "当前登录信息有误");
        }
        ApComment apComment = new ApComment();
        apComment.setAuthorId(apUser.getId());
        apComment.setAuthorName(apUser.getName());
        apComment.setContent(dto.getContent());
        apComment.setEntryId(dto.getArticleId());
        apComment.setCreatedTime(new Date());
        apComment.setLikes(0);
        apComment.setReply(0);
        apComment.setFlag(0);
        apComment.setType(0);
        mongoTemplate.insert(apComment);


        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
